import {
	defineStore
} from 'pinia';

export const useVoiceReadStore = defineStore('voiceRead', {
	state: () => ({
		// 朗读状态
		isReading: false,
		isPaused: false,
		
		// 朗读配置
		rate: 1, // 语速
		pitch: 1, // 音调
		voiceType: 'female', // 声音类型：female, male, youngMale, femaleHost, child
		
		// 音频上下文
		audioContext: null,
		
		// 朗读内容
		readingText: '',
		currentPosition: 0,
		
		// 其他设置
		preventPageTurn: false, // 阻止翻页
		autoNextPage: true, // 自动翻页
		shouldStopOnClose: false, // 关闭界面时是否停止朗读
		
		// 定时相关
		startTime: 0,
		timing: '00:00',
		timer: null,
		
		// 错误状态
		error: null
	}),
	
	getters: {
		// 是否正在朗读（包括暂停状态）
		isActive: (state) => {
			return state.isReading;
		}
	},
	
	actions: {
		// 开始朗读
		startReading(text) {
			if (!text || text.trim() === '') {
				this.error = '没有内容可朗读';
				uni.showToast({
					title: '当前页面没有内容可朗读',
					icon: 'none'
				});
				return;
			}
			
			// 如果已经在朗读，先停止
			if (this.isReading) {
				this.stopReading();
			}
			
			this.readingText = text;
			this.error = null;
			
			try {
				// 确保先销毁之前的实例
				if (this.audioContext) {
					try {
						this.audioContext.stop();
						this.audioContext.destroy();
					} catch (e) {
						console.error('销毁音频实例失败:', e);
					}
					this.audioContext = null;
				}
				
				// 创建新的音频上下文
				this.audioContext = uni.createInnerAudioContext();
				
				// 设置音频属性
				this.audioContext.autoplay = true; // 自动播放
				
				try {
					// 尝试设置忽略静音开关，但这个属性在某些平台可能不支持
					this.audioContext.obeyMuteSwitch = false;
				} catch (e) {
					console.log('该平台不支持设置obeyMuteSwitch属性');
				}
				
				// 设置音量
				this.audioContext.volume = 1;
				
				// 限制文本长度，避免请求过大
				const maxLength = 100; // 最多100个字符
				const trimmedContent = text.length > maxLength ? 
					text.substring(0, maxLength) + '...' : 
					text;
				
				const encodedText = encodeURIComponent(trimmedContent);
				
				// 根据语速和声音类型选择适当的API参数
				let spd = Math.round(this.rate * 5); // 将rate转换为1-10的整数
				if (spd < 1) spd = 1;
				if (spd > 10) spd = 10;
				
				// 使用百度翻译API
				const apiUrl = `https://fanyi.baidu.com/gettts?lan=zh&text=${encodedText}&spd=${spd}&source=web`;
				
				console.log('准备加载音频:', apiUrl);
				
				// 设置音频源
				this.audioContext.src = apiUrl;
				
				// 监听音频加载完成事件
				this.audioContext.onCanplay(() => {
					console.log('音频已准备好播放');
					this.isReading = true;
					this.isPaused = false;
				});
				
				// 监听播放开始事件
				this.audioContext.onPlay(() => {
					console.log('开始播放音频');
					this.isReading = true;
					this.isPaused = false;
				});
				
				// 监听播放结束事件
				this.audioContext.onEnded(() => {
					console.log('播放结束');
					this.isReading = false;
					this.isPaused = false;
					
					// 如果启用了自动翻页，继续朗读下一页
					if (this.autoNextPage) {
						uni.$emit('voiceReadNextPage');
					}
				});
				
				// 监听错误事件
				this.audioContext.onError((res) => {
					console.error('音频播放错误:', res);
					
					// 尝试使用另一种API作为备选
					if (res.errCode === -99 || res.errCode === 10001 || res.errCode === 10002) {
						console.log('尝试使用备选TTS API');
						
						// 销毁当前实例
						try {
							this.audioContext.destroy();
						} catch (e) {}
						
						// 创建新的音频实例
						this.audioContext = uni.createInnerAudioContext();
						this.audioContext.autoplay = true;
						
						// 使用备选API - 有道语音API
						const backupApiUrl = `https://tts.youdao.com/fanyivoice?word=${encodedText}&le=zh&keyfrom=speaker-target`;
						
						console.log('尝试备选API:', backupApiUrl);
						this.audioContext.src = backupApiUrl;
						
						// 设置事件监听
						this.audioContext.onPlay(() => {
							console.log('备选API开始播放');
							this.isReading = true;
							this.isPaused = false;
						});
						
						this.audioContext.onError((err) => {
							console.error('备选API也失败了:', err);
							
							try {
								this.audioContext.destroy();
							} catch (e) {}
							
							uni.showToast({
								title: '语音朗读功能暂不可用',
								icon: 'none'
							});
							this.isReading = false;
							this.isPaused = false;
							this.error = '语音朗读功能暂不可用';
							
							// 清理资源
							try {
								this.audioContext.destroy();
								this.audioContext = null;
							} catch (e) {}
						});
					} else {
						uni.showToast({
							title: '语音朗读出错',
							icon: 'none'
						});
						this.isReading = false;
						this.isPaused = false;
						this.error = '语音朗读出错';
					}
				});
				
				console.log('开始语音朗读:', text.substring(0, 50) + '...');
				
				// 设置阻止翻页
				this.preventPageTurn = true;
				
				// 开始计时
				this.startTimer();
				
			} catch (error) {
				console.error('语音朗读初始化失败:', error);
				uni.showToast({
					title: '您的设备不支持语音朗读',
					icon: 'none'
				});
				this.error = '您的设备不支持语音朗读';
			}
		},
		
		// 暂停朗读
		pauseReading() {
			if (!this.isReading || this.isPaused || !this.audioContext) return;
			
			try {
				this.audioContext.pause();
				this.isPaused = true;
				console.log('暂停朗读');
			} catch (error) {
				console.error('暂停朗读失败:', error);
				this.error = '暂停朗读失败';
			}
		},
		
		// 继续朗读
		resumeReading() {
			if (!this.isReading || !this.isPaused || !this.audioContext) return;
			
			try {
				this.audioContext.play();
				this.isPaused = false;
				console.log('继续朗读');
			} catch (error) {
				console.error('继续朗读失败:', error);
				this.error = '继续朗读失败';
			}
		},
		
		// 停止朗读
		stopReading() {
			if (!this.isReading && !this.audioContext) return;
			
			try {
				if (this.audioContext) {
					// 先暂停再销毁，避免直接销毁引起的问题
					try {
						this.audioContext.pause();
					} catch (e) {}
					
					try {
						this.audioContext.stop();
					} catch (e) {}
					
					try {
						this.audioContext.destroy(); // 销毁实例，避免-99错误
					} catch (e) {}
					
					this.audioContext = null;
				}
				
				this.isReading = false;
				this.isPaused = false;
				this.currentPosition = 0;
				console.log('停止朗读');
				
				// 停止计时
				this.stopTimer();
				
			} catch (error) {
				console.error('停止朗读失败:', error);
				this.error = '停止朗读失败';
			}
			
			// 取消阻止翻页
			this.preventPageTurn = false;
		},
		
		// 更新语音设置
		updateVoiceSettings(settings) {
			if (settings.rate !== undefined) this.rate = settings.rate;
			if (settings.pitch !== undefined) this.pitch = settings.pitch;
			if (settings.voiceType !== undefined) this.voiceType = settings.voiceType;
			
			// 根据声音类型设置参数
			if (settings.voiceType) {
				switch (settings.voiceType) {
					case 'female':
						this.pitch = 1.2;
						break;
					case 'male':
						this.pitch = 0.8;
						break;
					case 'youngMale':
						this.pitch = 1.0;
						this.rate = 1.1;
						break;
					case 'femaleHost':
						this.pitch = 1.3;
						this.rate = 0.9;
						break;
					case 'child':
						this.pitch = 1.5;
						this.rate = 1.2;
						break;
					default:
						this.pitch = 1.0;
						this.rate = 1.0;
				}
			}
			
			// 如果正在朗读，应用新的设置需要重启朗读
			if (this.isReading && this.audioContext) {
				const wasPaused = this.isPaused;
				const currentText = this.readingText;
				
				// 停止当前朗读
				try {
					this.audioContext.stop();
				} catch (e) {}
				
				// 重新开始朗读
				this.startReading(currentText);
				
				// 如果之前是暂停状态，继续暂停
				if (wasPaused) {
					setTimeout(() => {
						this.pauseReading();
					}, 100);
				}
			}
		},
		
		// 开始计时器
		startTimer() {
			this.startTime = Date.now();
			this.timing = '00:00';
			
			// 清除可能存在的旧计时器
			this.stopTimer();
			
			// 创建新计时器
			this.timer = setInterval(this.updateTimer, 1000);
		},
		
		// 停止计时器
		stopTimer() {
			if (this.timer) {
				clearInterval(this.timer);
				this.timer = null;
			}
		},
		
		// 更新计时器显示
		updateTimer() {
			const elapsed = Math.floor((Date.now() - this.startTime) / 1000);
			const minutes = Math.floor(elapsed / 60).toString().padStart(2, '0');
			const seconds = (elapsed % 60).toString().padStart(2, '0');
			this.timing = `${minutes}:${seconds}`;
		},
		
		// 重置状态
		reset() {
			this.stopReading();
			this.rate = 1;
			this.pitch = 1;
			this.voiceType = 'female';
			this.error = null;
			this.readingText = '';
			this.currentPosition = 0;
			this.preventPageTurn = false;
			this.autoNextPage = true;
		}
	}
}); 